package com.woniuxy.util;

import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;

import java.text.ParseException;
import java.util.Map;

public class JWTUtil {
    public static final String secretKey = "天王盖地虎，宝塔镇河妖";
    public static String createJWT(Map map) throws JOSEException {
        //生成JWT，头部+载荷+签名
        //1.生成头部
        JWSHeader header = new JWSHeader
                .Builder(JWSAlgorithm.HS256)//设置加密方式
                .type(JOSEObjectType.JWT).build();//设置JWT常量
//        System.out.println(header.toBase64URL());

        //2.生成载荷，用来保存用户登录信息(不要放密码等敏感信息)
//        Map map = new HashMap();
//        map.put("id", "1");
//        map.put("account", "admin");
        Payload payload = new Payload(map);
//        System.out.println(payload.toBase64URL());

        //3:签名 加密 （头部+载荷+密钥）每个系统自己设置
        JWSObject jwsObject = new JWSObject(header, payload);

        MACSigner macSigner = new MACSigner(secretKey);//MACSinger对称加密方式
        jwsObject.sign(macSigner);//数字签名(加密)

        //序列化得到jwt字符串
        //        System.out.println(jwtStr);

        return jwsObject.serialize();

    }

    //解密方法
    public  static  Boolean decode(String jwt) throws ParseException, JOSEException {
        //通过jwt字符串反序列化得到JWTObject对象
        JWSObject jwsObject = JWSObject.parse(jwt);
        MACVerifier macVerifier = new MACVerifier(secretKey);
        return jwsObject.verify(macVerifier);
    }

    //获取jwt中的用户信息(载荷)
    public  static  Map<String,Object> getUserMap(String jwt) throws ParseException {
        JWSObject jwsObject = JWSObject.parse(jwt);
        return jwsObject.getPayload().toJSONObject();
    }

}
